package com.zerui.manager.app.accessauthorg.executer;

import com.alibaba.cola.catchlog.CatchAndLog;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zerui.basedata.client.OrganizationService;
import com.zerui.cola.dto.MultiResponse;
import com.zerui.cola.dto.Response;
import com.zerui.manager.accessauthdevice.domainservice.AccessAuthDeviceRepository;
import com.zerui.manager.accessauthorg.AccessAuthOrg;
import com.zerui.manager.accessauthorg.domainservice.AccessAuthOrgRepository;
import com.zerui.manager.accessauthorg.gateway.AccessAuthOrgGateWay;
import com.zerui.manager.web.cmd.AccessAuthOrgBindCmd;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author wh
 * @create_time 2023-08-30 9:52
 */
@Component
@CatchAndLog
public class AccessAuthOrgAddCmdExe {

    @Resource
    private AccessAuthOrgGateWay accessAuthOrgGateWay;
    @Resource
    private AccessAuthOrgRepository accessAuthOrgRepository;
    @Resource
    private AccessAuthDeviceRepository accessAuthDeviceRepository;
    @Resource
    private OrganizationService organizationService;

    public Response execute(AccessAuthOrgBindCmd cmd) {

        List<Long> orgIds = cmd.getOrgIds();
        MultiResponse<Long> response = organizationService.queryOrganizationByParentIds(orgIds);
        List<Long> departmentIds = response.getData();
        //已经被绑定的部门
        Map<Long, Long> authIdMapByOrgIds = accessAuthOrgGateWay.getAuthIdMapByOrgIds(departmentIds);
        List<AccessAuthOrg> accessAuthOrg = new ArrayList<>();

        departmentIds.forEach(e->{
            if(!authIdMapByOrgIds.containsKey(e)){
                accessAuthOrg.add(AccessAuthOrg.builder()
                        .accessAuthId(cmd.getAccessAuthId())
                        .orgId(e)
                        .createTime(LocalDateTime.now())
                        .build());
            }
        });
        if(CollectionUtils.isNotEmpty(accessAuthOrg)){

            accessAuthOrgRepository.addBatch(accessAuthOrg);
            //下发
            List<Long> distributeOrgIds = accessAuthOrg
                    .stream()
                    .map(AccessAuthOrg::getOrgId)
                    .collect(Collectors.toList());
            accessAuthDeviceRepository.devicesDistributePermissionsByOrges(cmd.getAccessAuthId(),distributeOrgIds);
        }
        return Response.buildSuccess();

    }
}
